from django.shortcuts import render
from django.http import HttpResponse
from web.settings import BASE_DIR
from .. import models

# Create your views here.
from django.core.paginator import Paginator
from django.core.urlresolvers import reverse
from . viewsIndex import uploads
import time,os


# 商品添加
def goodsadd(request):

    # 获取所有商品分类数据
    data = models.Cates.objects.extra(select = {'paths':'concat(path,id)'}).order_by('paths')
    # 分配数据
    context = {'cateslist':data}       

    return render(request,'myadmin/goods/add.html',context)

# 商品数据添加
def goodsinsert(request):
    # 接收数据
    data = request.POST.dict()
    data.pop('csrfmiddlewaretoken')
    data['cateid'] = models.Cates.objects.get(id=data['cateid'])
    # print('1234567')
    # 处理上传的商品主图
    myfile = request.FILES.get('pic_url')
    if myfile:
        data['pic_url'] = uploads(myfile)

    else:
        return HttpResponse('<script>alert("未上传商品主图");history.back(-1);</script>')
    # 添加数据
    db = models.Goods(**data)
    db.save()

    return HttpResponse('<script>alert("添加成功");location.href="'+reverse('myadmin_goods_index')+'"</script>')

# 商品数据显示
def goodsindex(request):

    # 获取所有商品的数据
    data = models.Goods.objects.all()

    # 获取搜索条件,和参数
    types = request.GET.get('types')
    keywords = request.GET.get('keywords')

    # 判断筛选条件
    if types:
        # 判断搜索的类型
        if types == 'title':
            data = data.filter(title__contains=keywords)
        elif types == 'price':
            # 获取价格区间
            arr = keywords.split('-')
            data = data.filter(price__gte=arr[0]).filter(price__lte=arr[1])

        elif types == 'status':
            arr = {'上架':0,'热卖':1,'下架':2,'':0}
            data = data.filter(status=arr[keywords])

    # 数据分页
    paginator = Paginator(data,5)
    # 获取当前页码数
    p = request.GET.get('p',1)
    # 获取当前页的数据
    goodslist = paginator.page(p)

    # 分配数据
    context = {'goodslist':goodslist}

    # 加载模块
    return render(request,'myadmin/goods/index.html',context)
 
#删除(下架)商品数据
def goodsdel(request,gid):
    try:
        gdata = models.Goods.objects.get(id=gid)
        gdata.status = 2
        gdata.save()

        return HttpResponse('<script>alert("商品下架成功！");location.href="'+reverse('myadmin_goods_index')+'"</script>')
    except:
        return HttpResponse('<script>alert("商品下架失败！");location.href="'+reverse('myadmin_goods_index')+'"</script>')

# 修改商品信息
def goodsedit(request):

    # 获取传递的商品id
    gid = request.GET.get('gid')

    # 获取修改商品的信息
    gdata = models.Goods.objects.get(id=gid)

    # 获取所有商品分类数据
    data = models.Cates.objects.extra(select = {'paths':'concat(path,id)'}).order_by('paths')
      
    # 判断请求方式
    if request.method == 'GET':
        # 显示编辑表单
        return render(request,'myadmin/goods/edit.html',{'goodsinfo':gdata,'goodslist':data})

    elif request.method == 'POST':
        data = request.POST.dict()
        data.pop('csrfmiddlewaretoken')
        gdata.cateid = models.Cates.objects.get(id = data['cateid'])
        gdata.title = data['title']
        gdata.price = data['price']
        gdata.store = data['store']
        gdata.status = data['status']
        gdata.info = data['info']
        # 判断是否更新了商品主图
        myfile = request.FILES.get('pic_url')
        if myfile:
            # 如果修改了主图,要上传新的主图,并判断是否删除以前的主图
            if gdata.pic_url !='/static/pics/user.jpg':
                # 删除原来上传的主图
                os.remove(BASE_DIR+gdata.pic_url)
            # 更新主图
            gdata.pic_url = uploads(myfile)
        # 更新
        gdata.save()

        return HttpResponse('<script>alert("商品信息更新成功！");location.href="'+reverse('myadmin_goods_index')+'"</script>')
